<?php
require 'System/Forms/DocentForm.php';

class DocentController extends Controller
{
	protected $requiresAuthentication = true;
	
	/**
	 * 
	 * @see Controller::defaultAction()
	 */
	public function defaultAction()
	{
		$view = new HTMLView( 'DocentController/Overview', $this->getSmarty() );
		$view->assign( 'docenten', Docent::find('all') );
		
		$this->getViewManager()->push( $view );
	}
	
	public function createAction()
	{
		$this->showForm( );
	}
	
	public function editAction()
	{
		if( isset( $_GET['id'] ) )
		{
			$docent = Docent::find( $_GET['id'] );

			if( $docent == null )
			{
				throw new Exception('Docent with id ' . $_GET['id'] . ' was not found.');
			}
				
			$this->showForm( $docent );
		}
		else
		{
			$this->defaultAction();
		}
	}
	
	public function showForm( Docent $data = null )
	{
		$attributes = array();
		
		if( $data != null )
		{
			$attributes = $data->getAttributes();
			$view = new HTMLView( 'DocentController/Edit', $this->getSmarty() );
			$view->assign( 'docent', $data );
		}
		else
		{
			$view = new HTMLView( 'DocentController/Create', $this->getSmarty() );
		}
		
		$this->form_Step1( $view, $attributes );
	}
	
	private function form_Step1( View $view, $data = array() )
	{
		$docent = new DocentForm( $_SERVER['REQUEST_METHOD'] == 'POST' ? $_POST : $data );
		
		$view->assignArray( array( 'form' => $docent, 'step' => 1 ) );

		$this->getViewManager()->remove( $view );
		$this->getViewManager()->push( $view );
				
		if( $_SERVER['REQUEST_METHOD'] == 'POST' && $docent->isValid() )
		{
			$docent = new Docent( $_POST );
			$docent->save();
			
			// Show the confirmation.
			$this->form_ViewConfirmation( $docent );
			return;
		}
	}
	
	private function form_ViewConfirmation( Docent $docent )
	{
		header('Location: ?c=docent&a=detail&id=' . $docent->getSugarId());
	}
	
	public function detailAction()
	{
		if( isset( $_GET['id'] ) )
		{
			$docent = Docent::find( $_GET['id'] );

			if( $docent == null )
			{
				throw new Exception('Docent with id ' . $_GET['id'] . ' was not found.');
			}

			$view = new HTMLView( 'DocentController/Detail', $this->getSmarty() );
			$view->assign( 'docent', $docent );
			$this->getViewManager()->push( $view );
		}
		else
		{
			$this->defaultAction();
		}
	}
	
	public function deleteAction()
	{
		if( isset( $_GET['id'] ) )
		{
			$docent = Docent::find( $_GET['id'] );

			if( $docent == null )
			{
				throw new Exception('Docent with id ' . $_GET['id'] . ' was not found.');
			}

			$docent->delete();
		}
		
		$this->defaultAction();
	}
}